const util = require('util');
const debug = util.debuglog('oil-game:exchangeEssence:cache');
const uuid = require('node-uuid');
const {
  getInitExChangeByMongo,   //从Mongo中查询用户交易所表单信息
  delExchangeByUid,   //清空旧的数据
  saveExchangeFrom,   //添加新的交易所信息
  getHistoryTax,   //获取近三日交易所信息
  getNowExchangeList,   //返回最新的N条交易完成数据
} = require('./dao');
const {
  Msg,
} = require('./consts');
const {
  getFewDayAge,   //获取前几日的日期
} = require('./util');

//查看内存中User的交易所表单信息
exports.getUserExchangeData = async function(uid){
  //用户离线
  let user = await this.app.userRemote(uid, 'get', [uid, 'user']);
  if(!user){ 
    debug("用户 %s 获取交易所信息，内存中没有此用户，返回null", uid);
    return null;
  }
  //如果内存中有此数据，则直接返回
  if(user.exchangeEssence && user.exchangeEssence.type == 0) return user.exchangeEssence;
  //如果内存中不存在该表单数据，则从数据库中查询
  let exchange = await getInitExChangeByMongo(user.uid) || {};
  //更新内存中数据
  await this.app.userRemote(user.uid, "set", [user.uid, "user.exchangeEssence", exchange]);
  //返回从数据库查询的数据
  return exchange;
}

//初始化交易所表单信息
exports.initExchangeFrom = async function(uid, oilNum, house){
  //获取用户数据
  let user = await this.app.userRemote(uid, 'get', [uid, 'user']);
  let nickname = user && user.nickname;
  //初始化内存数据
  await exports.getUserExchangeData.call(this, uid);
  let id = uuid.v4();
  //设置交易所信息
  let created_at = new Date().valueOf();
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence", { id, nickname, uid, house, type: 0, oilNum, created_at }]);
}

//确认交易
exports.confirmExchange = async function(uid, money){
  //初始化内存数据
  await exports.getUserExchangeData.call(this, uid);
  //更新表单状态
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence.type", 1]);
  //更新可得现金
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence.money", money]);
  //更新时间
  let updated_at = new Date().valueOf();
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence.updated_at", updated_at]);
  //同步数据到数据库
  let exchange = await this.app.userRemote(uid, 'get', [uid, 'user.exchangeEssence']);
  await exports.syncExchangeFrom(exchange);
  //清空内存中数据
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence", null]);
}

//取消交易，更新订单状态
exports.cancelExchange = async function(uid, oilNum){
  //初始化内存数据
  await exports.getUserExchangeData.call(this, uid);
  //更新表单状态
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence.type", 2]);
  //同步数据到数据库
  let exchange = await this.app.userRemote(uid, 'get', [uid, 'user.exchangeEssence']);
  await exports.syncExchangeFrom(exchange);
  //清空内存中数据
  await this.app.userRemote(uid, "set", [uid, "user.exchangeEssence", null]);
}

//同步交易所信息到数据库
exports.syncExchangeFrom = async function(exchange) {
  let { uid } = exchange;
  //添加交易所信息
  await saveExchangeFrom(exchange);
}

//获取近三日交易所信息
exports.getHistoryTax = async function(){
  let oneFewDayAge = getFewDayAge(-1);
  let twoFewDayAge = getFewDayAge(-2);
  let threeFewDayAge = getFewDayAge(-3);
  debug("获取近三日交易所信息");
  //获取前几日交易所的信息
  let history_tax = await getHistoryTax.call(this, oneFewDayAge, twoFewDayAge, threeFewDayAge);
  if(!(Array.isArray(history_tax) && history_tax.length >= 0)){
    debug("获取近三日交易所信息异常，查找异常 %s", JSON.stringify(history_tax));
    throw new Error(Msg.HISTORY_TAX_ERR);
  }
  let tokyo = [];   //东京    1
  let london = [];    //伦敦    2
  let newYork = [];   //纽约    3
  //分类
  for(let i = 0; i < history_tax.length; i++){
    let item = history_tax[i];
    let date = item.date;    //日期
    date = date.slice(date.indexOf('-')+1).replace('-','/');
    switch(item.exchange_id){
      case 1:
        tokyo.push({date, tax: item.price});
        break;
      case 2:
        london.push({date, tax: item.price});
        break;
      case 3:
        newYork.push({date, tax: item.price});
        break;
    }
  }
  //排序
  tokyo = tokyo.sort((tax1, tax2) => new Date(tax2.date) - new Date(tax1.date));
  london = london.sort((tax1, tax2) => new Date(tax2.date) - new Date(tax1.date));
  newYork = newYork.sort((tax1, tax2) => new Date(tax2.date) - new Date(tax1.date));
  return {tokyo, london, newYork};
}

//返回最新的N条交易完成数据
exports.getNowExchangeList = async function(num){
  return await getNowExchangeList.call(this, num);
}
